from odoo.addons.basic_configuration.functions.common_utils_fc import CommonUtils


class CustomerFunctions(object):
    """
    Model:
        满足客户的所有算法逻辑

    Param:
        - env: odoo env

    Function:
        - get_customer: 根据邮箱检验客户，有则获取，没有则创建
    """

    def __init__(self, env):
        self.env = env

    def get_customer(self, email, last_name, first_name):
        """
        根据邮箱检验客户，有则获取，没有则创建(rp.customer)

        :param email 邮箱
        :param last_name  姓
        :param first_name 名

        @return customer(rp.customer)
        """
        rcd = self.env['rp.customer'].search([('email', '=', email)])
        if rcd:
            return rcd
        else:
            customer = self.env['rp.customer'].create([{"last_name": last_name,
                                                        "first_name": first_name,
                                                        "email": email}])
            return customer

    def pay_out(self, customer_balance_id, price):
        """
        支付后的余额计算
        Params:
        -customer_balance_id:客户余额
        -price:扣减金额
        """
        total_price = customer_balance_id.total_balance - price  # 扣除后的总金额
        actual_radio = customer_balance_id.actual_radio  # 实付比率
        # 新实付金额,赠送金额由实付金额得出
        actual_price = CommonUtils().always_ceil(total_price * actual_radio, 2)
        present_price = total_price - actual_price
        customer_balance_id.sudo().write({'actual_price': actual_price, 'present_price': present_price, 'total_balance': total_price})

    def pop_up(self, customer_balance_id):
        """
        充值后的余额计算
        """
        actual_price = customer_balance_id.actual_price  # 实付金额
        present_price = customer_balance_id.present_price  # 赠送金额
        # 新价格
        new_total_price = actual_price + present_price
        # 计算实付和赠送的比率问题，实付取大值，赠送由实付得出
        new_actual_radio = CommonUtils().always_ceil(actual_price / new_total_price, 4)
        new_present_radio = 1 - new_actual_radio
        customer_balance_id.write({
            'total_balance': new_total_price,
            'actual_price': actual_price,
            'present_price': present_price,
            'actual_radio': new_actual_radio,
            'present_radio': new_present_radio
        })
